#-*- coding:utf-8 -*-
import hashlib   
import os
import io
import sys
import shutil
import re

md5ListFileName = 'md5list.txt'

def printUsage():
	print ('''Usage: [python] pymd5sum.py ''')

def mymovefile(srcfile,dstfile):
    if not os.path.isfile(srcfile):
        if os.path.getsize(srcfile)>0:
            print "%s not exist!"%(srcfile)
        else:
            shutil.move(srcfile,dstfile)
            # shutil.rmtree(srcfile)
    else:
        fpath,fname=os.path.split(dstfile)
        if not os.path.exists(fpath):
            os.makedirs(fpath)
        shutil.move(srcfile,dstfile)
        print "move %s -> %s"%( srcfile,dstfile)

def geneMd5(filename):
    return 'fuckMd5'
    m = hashlib.md5()
    file = io.FileIO(filename,'r')
    bytes = file.read(1024)
    while(bytes != b''):
        m.update(bytes)
        bytes = file.read(1024) 
    file.close()
    return m.hexdigest()
def main():
    if(len(sys.argv) != 1 and len(sys.argv) != 2):
        printUsage()
    if(len(sys.argv)==1):
        path="./"
    if(len(sys.argv)==2):
        path=sys.argv[1]
    if os.path.exists(md5ListFileName):
        with open(md5ListFileName, 'r') as f:
            md5List = f.readlines()
            for i in range(0, len(md5List)):
                md5List[i] = md5List[i].rstrip('\n')
            for fpathe,dirs,fs in os.walk(path):
                for f in fs:
                    full_file = os.path.join(fpathe,f)
                    md5 = geneMd5(full_file)
                    if (full_file + "|"+md5) not in md5List and not full_file.startswith('./md5list')  and full_file != ('./'+ os.path.basename(__file__)) and re.match('./fileListBack',full_file) == None:
                        mymovefile(full_file,re.sub(r'^.', './fileListBack', full_file, 1))
            dirList = []
            for fpathe,dirs,fs in os.walk(path):
                for d in dirs:
                    full_dir = os.path.join(fpathe,d)
                    if (full_dir + "\\") not in md5List and full_dir != ('./'+ os.path.basename(__file__)) and re.match('./fileListBack',full_dir) == None:
                        dirList.append(full_dir)
            
            dirList.reverse()
            for full_dir in dirList:
                mymovefile(full_dir,re.sub(r'^.', './fileListBack', full_dir, 1))

        pass
main()